package org.example.service.impl;

import org.example.domain.*;
import org.example.mapper.FruitMapper;
import org.example.mapper.InventoryMapper;
import org.example.mapper.OrderMapper;
import org.example.mapper.OrderItemMapper;
import org.example.mapper.PaymentRecordMapper;
import org.example.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Service
public class OrderServiceImpl implements OrderService {

    private static final Logger log = LoggerFactory.getLogger(OrderServiceImpl.class);

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private FruitMapper fruitMapper;
    @Autowired
    private OrderItemMapper orderItemMapper;
    @Autowired
    private InventoryMapper inventoryMapper;
    @Autowired
    private PaymentRecordMapper paymentRecordMapper;

    @Override
    public List<Map<String, Object>> getOrderList(String userId) {
        List<Order> orders = orderMapper.selectByUserId(userId);
        List<Map<String, Object>> result = new ArrayList<>();
        
        for (Order order : orders) {
            Map<String, Object> orderMap = new HashMap<>();
            orderMap.put("id", order.getId());
            orderMap.put("orderNo", order.getOrderNo());
            orderMap.put("status", order.getStatus());
            orderMap.put("createTime", order.getCreateTime());
            orderMap.put("totalAmount", order.getTotalAmount());
            result.add(orderMap);
        }
        
        return result;
    }

    @Override
    public List<Map<String, Object>> getOrderItems(Long orderId) {
        List<OrderItem> items = orderItemMapper.selectByOrderId(orderId);
        List<Map<String, Object>> result = new ArrayList<>();
        
        for (OrderItem item : items) {
            Map<String, Object> itemMap = new HashMap<>();
            //根据每一项ID,查询水果信息
            Fruit fruit = fruitMapper.selectById(item.getFruitId());
            itemMap.put("id", item.getId());
            itemMap.put("fruitId", item.getFruitId());
            itemMap.put("quantity", item.getQuantity());
            itemMap.put("price", item.getPrice());
            itemMap.put("totalPrice", item.getTotalPrice());
            itemMap.put("image", fruit.getImage());
            itemMap.put("name", fruit.getName());
            result.add(itemMap);
        }
        
        return result;
    }

    @Override
    @Transactional
    public void cancelOrder(Long orderId) {
        Order order = orderMapper.selectById(orderId);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }
        
        if (!"待支付".equals(order.getStatus())) {
            throw new RuntimeException("只能取消待支付的订单");
        }
        
        // 获取订单项
        List<OrderItem> orderItems = orderItemMapper.selectByOrderId(orderId);
        // 恢复库存
        rebackStock(orderItems);
        order.setStatus("已取消");
        orderMapper.updateById(order);
    }
    //TODO
    private void rebackStock(List<OrderItem> orderItems) {
        for (OrderItem item : orderItems) {
            //根据水果ID查询库存ID
            Long inventoryID=inventoryMapper.selectinventoryIDByFruitId(item.getFruitId());
            FruitInventory inventory = inventoryMapper.selectById(inventoryID);
            if (inventory != null) {
                // 恢复库存数量
                BigDecimal newStock = inventory.getStock().add(BigDecimal.valueOf(item.getQuantity()));
                inventory.setStock(newStock);
                inventoryMapper.updateById(inventory);
            }
        }
    }

    @Override
    @Transactional
    public void mockPaySuccess(String orderId) {
        log.info("处理模拟支付成功：{}", orderId);
        
        // 1. 验证订单是否存在
        Order order = orderMapper.selectById(orderId);
        if (order == null) {
            throw new RuntimeException("订单不存在：" + orderId);
        }
        
        // 2. 更新订单状态
        order.setStatus("已支付"); // 改为中文状态
        order.setPayTime(new Date());
        order.setTransactionId("TEST" + System.currentTimeMillis());
        orderMapper.updateById(order);
        
        // 3. 记录支付成功的流水
        PaymentRecord paymentRecord = new PaymentRecord();
        paymentRecord.setOrderId(orderId);
        paymentRecord.setPaymentNo("PAY" + System.currentTimeMillis());
        paymentRecord.setAmount(order.getTotalAmount());
        paymentRecord.setStatus("SUCCESS");
        paymentRecord.setPayTime(new Date());
        paymentRecord.setCreateTime(new Date());
        paymentRecord.setUpdateTime(new Date());
        paymentRecordMapper.insert(paymentRecord);
        
        log.info("订单{}支付成功处理完成", orderId);
    }
} 